$(function () {

    // 初始化数据
    initData();

    // 引入数据校验
    initCheckdata();

    // 给是否发送邮件绑定单击事件
    $("input[name='isSendEmail']").click(function () {
        showOrHiddenEmail($(this).val());
    });

    // 保存按钮
    $(".press_btn1").click(function () {
        saveEventAndAlerts();
    });

    // 关闭窗口
    $(".press_btn2").click(function () {
        closeWindows();
    });

    $("#eventSort").change(function () {
        selectEventTypeBySort(this);
    });
    
    $("#eventOwner").change(function () {
        selectEmailByEventOwner();
    })
    // $("#eventTypeDiv").bind("click", ".add", function (e) {
    //     selectEventOwnerByType(e.target);
    // })

});


function initData(){
    // 事件分类
    var div = '<option value="">请选择...</option>';
    $.each(all_event, function (eventSort, eventType) {
        div += '<option value="'+eventSort+'">'+eventSort+'</option>';
    });
    $("#eventSort").append(div);
    $("#eventSort").val(eventJson.eventSort);
    // 事件分级
    var div = '<option value="'+eventJson.eventType+'">'+eventJson.eventType+'</option>';
    $("#eventType").append(div);
    $("#eventType").val(eventJson.eventType);
    // 事件处理专员
    var ownerDiv = '<option value="">请选择...</option>';
    $.each(event_owner, function (owner, mail) {
        ownerDiv += '<option value="' + owner + '">' + owner + '</option>';
    });
    $("#eventOwner").append(ownerDiv);
    $("#eventOwner").val(eventJson.eventOwner);
    $("#threatLevel").val(eventJson.threatLevel);
    $("#eventDeptId").val(eventJson.eventDeptId);
    $("input[name='isSendEmail']").each(function (i, n) {
        if ($(this).val().trim() == eventJson.isSendEmail) {
            $(this).attr("checked", "checked");
        }
    });
    showOrHiddenEmail($("input[name='isSendEmail']:checked").val());
}

function selectEventTypeBySort(btn){
    $("#eventTypeDiv").html("");
    var div = '';
    var eventSort = $(btn).val().trim();
    if (eventSort != ''){
        $.each(all_event, function (sort, eventType) {
            if (eventSort == sort){
                if (eventType.length == 0) {
                    div += '<input id="eventType" class="form-control add" checkData="NotNull" placeholder="请输入具体原因" />';
                }else {
                    div += '<select id="eventType" class="form-control add" checkData="NotNull">';
                    $.each(eventType, function (i, type) {
                        div += '<option value="' + type +'">' + type + '</option>';
                    });
                    div += '</select>';
                }
                $("#eventTypeDiv").append(div);
            }
        })
    }else if (eventSort == '') {
        div += '<select id="eventType" class="form-control add" checkData="NotNull">' +
            '<option value="">请先选择事件分类...</option>' +
            '</select>';
        $("#eventTypeDiv").append(div);
    }
}

function selectEmailByEventOwner() {
    $("#emailToAddress").html("");
    var eventOwner = $("#eventOwner").val();
    if (eventOwner != null && eventOwner != "") {
        $.each(event_owner, function (owner, mail) {
            if (eventOwner == owner) {
                $("#emailToAddress").append(mail);
            }
        })
    }
}

// function selectEventOwnerByType(btn) {
//     $("#eventOwnerDiv").html("");
//     var sort = $("#eventSort").val();
//     var type = $(btn).val();
//     if (type != null && type != '') {
//         $.each(all_event, function (eventSort, eventType) {
//             if (eventSort == sort) {
//                 $.each(eventType, function (type_1, owner) {
//                     if (type == type_1) {
//                         var div = "<input id='eventOwner' class='form-control' disabled='disabled' value='"+owner+"'/>";
//                         $("#eventOwnerDiv").append(div);
//                     }
//                 })
//             }
//         })
//     }else {
//         var div = "<input id='eventOwner' class='form-control' checkData='NotNull' placeholder='请输入事件owner' />";
//         $("#eventOwnerDiv").append(div);
//     }
//     // 添加邮箱
//     $("#emailToAddress").html("");
//     var eventOwner = $("#eventOwner").val().trim();
//     $.each(event_owner, function (owner, mail) {
//         if (eventOwner != '' && eventOwner == owner) {
//             $("#emailToAddress").append(mail);
//         }
//     })
// }

function showOrHiddenEmail(flag) {
    if (flag == 0) {
        $("#email_title").hide();
        $("#email_body").hide();
    }else if (flag == 1){
        $("#email_title").show();
        $("#email_body").show();
    }
}

function saveEventAndAlerts() {

    // 校验
    var flag = checkData();
    if(!flag){
        return flag;
    }
    // 事件
    eventJson.eventSort = $("#eventSort").val().trim();
    eventJson.eventType = $("#eventType").val().trim();
    eventJson.eventDesc = $("#eventDesc").val().trim();
    eventJson.eventOwner = $("#eventOwner").val();
    eventJson.threatLevel = $("#threatLevel").val();
    eventJson.eventDeptId = $("#eventDeptId").val();
    eventJson.eventDeptName = $("#eventDeptId").find(":selected").text().trim();
    eventJson.isSendEmail = $("input[name='isSendEmail']:checked").val();
    if (eventJson.isSendEmail == 1) {
        var emailToAddress = $("#emailToAddress").val().trim();
        if (!checkEmail(emailToAddress)){
            return;
        }
        eventJson.emailToAddress = emailToAddress;
        eventJson.emailTitle = $("#emailTitle").val().trim();
        eventJson.emailContent = $("#emailContent").val().trim();
    }

    $.ajax({
        url: basePath + "/splunk/event/saveEventAfterEdit.do",
        type: "post",
        dataType: "json",
        data: {
            eventStr: JSON.stringify(eventJson)
        },
        success:function (json) {
            var code = json.code;
            if (code == '200') {
                parent.layer.msg("事件已保存", {time: 1500}, function () {
                    parent.initData();
                    closeWindows();
                });

            }else if (code == '500'){
                parent.layer.msg("事件保存失败", {time: 1500});
            }
        }
    });
    // 防止多次提交
    $(".press_btn1").addClass("disabled");
}

function closeWindows() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function checkEmail(address) {
    var flag = true;
    var index = 0;
    var addressArr = address.split(",");
    addressArr.forEach(function (i, n) {
        if (index == 0) {
            var reg = /^[A-Za-z\d]+([\-_\.][A-Za-z\d]+)*@([A-Za-z\d]+[\-\.])+[A-Za-z\d]{2,5}$/;
            if(!reg.test($.trim(i))) {
                parent.layer.msg("收件人地址邮箱格式不正确", {time: 1500});
                index++;
                flag = false;
            }
        }
    });
    return flag;
}